﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Top.Web;
using Top.Data;
using Top.Web.Api;

namespace Top.PointStore.Business
{
    public static class DataBaseSyncManager
    {
        public static List<Guid> TodayCheckUser_Broker = new List<Guid>();

        public static List<Guid> TodayCheckUser_Admin = new List<Guid>();

        private static DateTime LastUpdateTime = DateTime.Now.AddDays(-1);
        static DataBaseSyncManager()
        {

        }

        public static async Task<object> Broker_Sync(OAuthUser user)
        {
            using (var db = new DbTour())
            {
                string sql = @"
                SELECT
	                a.kid,
	                a.F_CityKid,
	                a.F_Title,
	                a.F_Phone,
	                a.F_AddTime,
	                a.F_EditTime,
	                a.F_BrokerCompanyKid,
	                a.F_BrokerCompanyName,
	                ifnull(b.F_IsDistribute, 0) AS IsFenXiao
                FROM
	                t_broker a
                LEFT JOIN t_brokercompany b ON a.F_BrokerCompanyKid = b.Kid where a.kid = {0} limit";
                T_Broker broker = await db.Sql(sql, user.BrokerID).FirstOrDefault<T_Broker>();
                if (broker == null)
                {
                    string sql2 = @"select * from T_Broker where kid = {0}";
                    using (var db2 = new DbTour("sqldefault"))
                    {
                        broker = await db2.Sql(sql2, user.BrokerID).FirstOrDefault<T_Broker>();
                    }
                    if (broker != null && broker.Kid > 0)
                    {
                        #region 插入Borker表
                        string sql3 = @"
INSERT INTO T_Broker
           (Kid
           ,F_ProvinceKid
           ,F_CityKid
           ,F_LocationCityKid
           ,F_Title
           ,F_Phone
           ,F_PassWord
           ,F_IDNumber
           ,F_AddTime
           ,F_EditTime
           ,F_WeiXinID
           ,F_PicUrl
           ,F_Status
           ,F_AuthTime
           ,F_PassTime
           ,F_RealTime
           ,F_LastActiveTime
           ,F_Bank
           ,F_BankAccount
           ,F_RecommendPhone
           ,F_WX_Nickname
           ,F_WX_Country
           ,F_WX_Province
           ,F_WX_City
           ,F_WX_Language
           ,F_WX_Sex
           ,F_WX_Subscribe
           ,F_WX_Subscribe_time
           ,F_Type
           ,F_BrokerCompanyName
           ,F_BrokerCompanyKid
           ,F_Longitude
           ,F_Latitude
           ,F_LastLocationTime
           ,F_FirstAgreementTime
           ,F_LastAgreementTime
           ,F_BusinessCardUrl
           ,F_TagIsSuperAuth
           ,F_TagIsSuperAuthTime
           ,F_TagYear
           ,F_TagProgramCount
           ,F_TagBusinessCount
           ,F_TagSpareAvgMoney
           ,F_TagCommentCount
           ,F_Tag
           ,F_Remark
           ,F_CheckInTime
           ,F_QrCode
           ,F_Ex
           ,F_DeviceID
           ,F_AppVersion
           ,F_HxUuid
           ,F_CardUrl
           ,F_CardCheckAdminKid
           ,F_CardCheckTime
           ,AnyangKid
           ,F_CardCheckStatus)
     VALUES
           ({0:Kid}
		   ,{0:F_ProvinceKid}
           ,{0:F_CityKid}
           ,{0:F_LocationCityKid}
           ,{0:F_Title}
           ,{0:F_Phone}
           ,{0:F_PassWord}
           ,{0:F_IDNumber}
           ,{0:F_AddTime}
           ,{0:F_EditTime}
           ,{0:F_WeiXinID}
           ,{0:F_PicUrl}
           ,{0:F_Status}
           ,{0:F_AuthTime}
           ,{0:F_PassTime}
           ,{0:F_RealTime}
           ,{0:F_LastActiveTime}
           ,{0:F_Bank}
           ,{0:F_BankAccount}
           ,{0:F_RecommendPhone}
           ,{0:F_WX_Nickname}
           ,{0:F_WX_Country}
           ,{0:F_WX_Province}
           ,{0:F_WX_City}
           ,{0:F_WX_Language}
           ,{0:F_WX_Sex}
           ,{0:F_WX_Subscribe}
           ,{0:F_WX_Subscribe_time}
           ,{0:F_Type}
           ,{0:F_BrokerCompanyName}
           ,{0:F_BrokerCompanyKid}
           ,{0:F_Longitude}
           ,{0:F_Latitude}
           ,{0:F_LastLocationTime}
           ,{0:F_FirstAgreementTime}
           ,{0:F_LastAgreementTime}
           ,{0:F_BusinessCardUrl}
           ,{0:F_TagIsSuperAuth}
           ,{0:F_TagIsSuperAuthTime}
           ,{0:F_TagYear}
           ,{0:F_TagProgramCount}
           ,{0:F_TagBusinessCount}
           ,{0:F_TagSpareAvgMoney}
           ,{0:F_TagCommentCount}
           ,{0:F_Tag}
           ,{0:F_Remark}
           ,{0:F_CheckInTime}
           ,{0:F_QrCode}
           ,{0:F_Ex}
           ,{0:F_DeviceID}
           ,{0:F_AppVersion}
           ,{0:F_HxUuid}
           ,{0:F_CardUrl}
           ,{0:F_CardCheckAdminKid}
           ,{0:F_CardCheckTime}
           ,{0:AnyangKid}
           ,{0:F_CardCheckStatus})
";
                        #endregion
                        int success = await db.Sql(sql3, broker).ExecuteNonQuery();
                        if (success == 0)
                        {
                            throw new WebApiException("积分商城新用户注册失败");
                        }
                    }
                    else
                    {
                        throw new WebApiException("无法拉取用户信息");
                    }
                    MemoryTable.TB_Broker.TryAdd(broker.Kid, broker);
                }
                else
                {
                    if (!MemoryTable.TB_Broker.Keys.Contains(user.BrokerID))
                    {
                        MemoryTable.TB_Broker.TryAdd(broker.Kid, broker);
                    }
                }
            }
            return 1;
        }

        public static async Task<object> Admin_Sync(OAuthUser user)
        {
            using (var db = new DbTour())
            {
                string sql = @"select count(1) from S_Admin where kid = {0}";
                int count = await db.Sql(sql, user.CrmUserID).FirstOrDefault<int>(0);
                if (count == 0)
                {
                    string sql2 = @"select * from S_Admin where kid = {0}";
                    S_Admin admin = new S_Admin();
                    using (var db2 = new DbTour("sqldefault"))
                    {
                        admin = await db2.Sql(sql2, user.CrmUserID).FirstOrDefault<S_Admin>();
                    }
                    if (admin != null && admin.Kid > 0)
                    {
                        #region 插入Admin表
                        string sql3 = @"
INSERT INTO S_Admin
           (Kid
           ,F_RoleID
           ,F_LoginName
           ,F_Password
           ,F_Number
           ,F_Email
           ,F_Sex
           ,F_RealName
           ,F_PicUrl
           ,F_QQ
           ,F_MSN
           ,F_CellPhone
           ,F_OfficePhone
           ,F_HomePhone
           ,F_Remark
           ,F_LastLoginTime
           ,F_LastLoginIP
           ,F_ThisLoginTime
           ,F_ThisLoginIP
           ,F_LoginCount
           ,F_DeviceID
           ,F_AppVersion
           ,F_AppBrokerVersion
           ,F_IsDefine
           ,F_DefineLength
           ,F_DefineTime
           ,F_Enabled
           ,F_AddTime
           ,F_AddAdminKid
           ,F_EditTime
           ,F_EditAdminKid
           ,F_BeginTime
           ,F_EndTime
           ,F_IsReceiveEmail
           ,F_Type
           ,X_Type
           ,X_BrokerCompanyKid
           ,X_FrameworkKid
           ,F_IsOpenDefine)
     VALUES
           ({0:Kid}
           ,{0:F_RoleID}
           ,{0:F_LoginName}
           ,{0:F_Password}
           ,{0:F_Number}
           ,{0:F_Email}
           ,{0:F_Sex}
           ,{0:F_RealName}
           ,{0:F_PicUrl}
           ,{0:F_QQ}
           ,{0:F_MSN}
           ,{0:F_CellPhone}
           ,{0:F_OfficePhone}
           ,{0:F_HomePhone}
           ,{0:F_Remark}
           ,{0:F_LastLoginTime}
           ,{0:F_LastLoginIP}
           ,{0:F_ThisLoginTime}
           ,{0:F_ThisLoginIP}
           ,{0:F_LoginCount}
           ,{0:F_DeviceID}
           ,{0:F_AppVersion}
           ,{0:F_AppBrokerVersion}
           ,{0:F_IsDefine}
           ,{0:F_DefineLength}
           ,{0:F_DefineTime}
           ,{0:F_Enabled}
           ,{0:F_AddTime}
           ,{0:F_AddAdminKid}
           ,{0:F_EditTime}
           ,{0:F_EditAdminKid}
           ,{0:F_BeginTime}
           ,{0:F_EndTime}
           ,{0:F_IsReceiveEmail}
           ,{0:F_Type}
           ,{0:X_Type}
           ,{0:X_BrokerCompanyKid}
           ,{0:X_FrameworkKid}
           ,{0:F_IsOpenDefine})
";
                        #endregion
                        int success = await db.Sql(sql3, admin).ExecuteNonQuery();
                        if (success == 0)
                        {
                            throw new WebApiException("积分商城新用户注册失败");
                        }
                    }
                    else
                    {
                        throw new WebApiException("无法拉取用户信息");
                    }
                }
                MemoryTable.TB_Admin.TryAdd(user.CrmUserID, new S_Admin());
            }
            return 1;
        }


        public static void SetTimeUpdate()
        {
            var clearTask = new Task(() =>
            {
                while (true)
                {
                    TimeSpan ts = DateTime.Now.Date - LastUpdateTime;
                    if (ts.Days > 0)
                    {
                        LastUpdateTime = DateTime.Now.Date;
                        TodayCheckUser_Broker.Clear();
                        TodayCheckUser_Admin.Clear();
                    }
                    Thread.Sleep(10000);
                }
            });
            clearTask.Start();
        }
    }
}
